package com.caoxw.Android.CityBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;

import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public final class CityBus extends Activity {

	static final int REQUEST_FOR_BUSINFO = 0;
	static final int REQUEST_FOR_CONFIG = 1;

	public ListView m_objStationsList;
	public ListView m_objBusesList;
	public EditText m_objStationEdit;
	public EditText m_objBusEdit;
	private TextView m_objInfoText;
	private String m_strStationA;
	private String m_strStationB;
	private int m_intStationSelected = 0;
	private  ProgressDialog m_pDialog = null;
	private ImageButton m_objSetStationA, m_objSetStationB, m_objConfigButton,
			m_objSearchLines;
	private ProgressDialog m_dlgProcessgress;
	private Handler hander = null;
	private final static int MENU_ABOUT = 1;
	private final static int MENU_QUIT = 2;
	private final static int MENU_CONFIG = 3;
	private Update m_objUpdateThread = null;
	
	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		System.out.println(getPackageName());
		setContentView(R.layout.main);
		m_objStationsList = (ListView) findViewById(R.id.stationsList);
		m_objBusesList = (ListView) findViewById(R.id.busesList);
		m_objStationEdit = (EditText) findViewById(R.id.editText1);
		m_objBusEdit = (EditText) findViewById(R.id.editText2);
		m_objInfoText = (TextView) findViewById(R.id.textView1);

		m_objSetStationA = (ImageButton) findViewById(R.id.setStationA);
		m_objSetStationB = (ImageButton) findViewById(R.id.setStationB);
		m_objSearchLines = (ImageButton) findViewById(R.id.searchlines);
		m_objConfigButton = (ImageButton) findViewById(R.id.About);
		
		m_dlgProcessgress = new ProgressDialog(CityBus.this);
		
		m_pDialog = new ProgressDialog(CityBus.this);
		m_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		hander = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case BusScan.MSG_BUSCAN_SEARCHLINES_START:
					// .show(CityBus.this, "Searching....", "", true, true);
					m_dlgProcessgress.setButton("cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int i) {
									// dialog.cancel();
									m_dlgProcessgress.setMessage("正在取消...");
									((CityBusApp) getApplicationContext()).m_objBusScan
											.Cancel();
								}
							});
					m_dlgProcessgress
							.setOnCancelListener(new DialogInterface.OnCancelListener() {
								public void onCancel(DialogInterface dialog) {
									// finish();
								}
							});
					m_dlgProcessgress.setCancelable(true);
					m_dlgProcessgress.setTitle("Waiting...");
					m_dlgProcessgress.setMessage("正在查找换乘线路，请稍后...");
					m_dlgProcessgress.show();
					break;
				case BusScan.MSG_BUSCAN_SEARCHLINES_PROCESSING:
					if(msg.arg1 == 0)
						m_dlgProcessgress.setMessage("正在查找直达线路，请稍后...");
					else
						m_dlgProcessgress.setMessage("正在查找 " + msg.arg1 + " 次换乘线路，请稍后...");
					m_dlgProcessgress.show();
					break;
				case BusScan.MSG_BUSCAN_SEARCHLINES_FINISED:
					m_dlgProcessgress.dismiss();
					((CityBusApp) getApplicationContext()).m_objBusScan.PutChangBusLines((LinesStruct) msg.obj);
					if(((LinesStruct) msg.obj).isEmpty()){
						Toast.makeText(getApplicationContext(),  "没有找到可乘线路",
								Toast.LENGTH_SHORT).show();
						return ;
					}
					Intent intent = new Intent(getApplicationContext(),
							ShowLinesActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("StationA", m_strStationA);
					bundle.putString("StationB", m_strStationB);
					intent.putExtras(bundle);
					startActivityForResult(intent, 0);
					break;
				case BusScan.MSG_BUSCAN_ERROR:
					m_dlgProcessgress.setMessage((String)msg.obj);
					m_dlgProcessgress.show();
					break;
				case Update.MSG_FLAG_DOWNLOAD_APP_START:
					m_pDialog.setTitle("Waiting");
					m_pDialog.setMessage("正在连接升级服务器 ...");
					m_pDialog.show();
					break;
					
				case Update.MSG_FLAG_DOWNLOAD_APP_PROCESS:
					m_pDialog.setMax(msg.arg2/1024);
					m_pDialog.setProgress(msg.arg1/1024);
					m_pDialog.setMessage("正在下载最新文件，\n大小："+ String.valueOf(msg.arg2/1024)+"k");
					break;
				case Update.MSG_FLAG_DOWNLOAD_APP_FINISHED:
					m_pDialog.setMessage("下载完成，准备启动安装程序");
					Intent intent1 = new Intent(Intent.ACTION_VIEW); 
					intent1.setDataAndType(Uri.fromFile(new File((String)(msg.obj))),"application/vnd.android.package-archive"); 
					startActivity(intent1); 
					m_pDialog.dismiss();
					break;
				case Update.MSG_FLAG_DOWNLOAD_APP_ERROR:
					m_pDialog.dismiss();
					new AlertDialog.Builder(CityBus.this)
					.setMessage((String)(msg.obj))
					.setTitle("提示")
					.setPositiveButton("确认", new OnClickListener() {
						public void onClick(DialogInterface dialog,
								int which) {
							dialog.dismiss();
						}
					}).create().show();;
					
					break;
				case Update.MSG_FLAG_VERSION_APP_AVAILABLE:
					Builder builder = new AlertDialog.Builder(CityBus.this);
					builder.setMessage("发现新版本 ,版本代号为 " + String.valueOf(msg.arg1)+ ".0 ,\n是否现在升级？");
					builder.setTitle("提示");
					builder.setPositiveButton("确认", new OnClickListener() {
						public void onClick(DialogInterface dialog,
								int which) {
							dialog.dismiss();
							m_objUpdateThread.continueRun();
						}
					});
					builder.setNegativeButton("取消", new OnClickListener() {
						public void onClick(DialogInterface dialog,
								int which) {
							dialog.dismiss();
							m_objUpdateThread.stop();
						}
					});
					builder.create().show();
					break;
				}
			}
		};

		setListener();
		Init();
		m_objUpdateThread = new Update(getApplicationContext(),hander);
		if (((CityBusApp) getApplicationContext()).m_objConfigMgr.m_bolCheckVersion) {
			System.out.println("Start Thread.....");	
			m_objUpdateThread.start();
		}

	}

	public void showStationsList() {
		String strStation = m_objStationEdit.getText().toString();
		if (strStation.length() == 0)
			return;
		ArrayList<String> BusesList = ((CityBusApp) getApplicationContext()).m_objBusScan.ScanString(strStation, true);
		// 生成动态数组，加入数据
		ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < BusesList.size(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			// map.put("ItemImage", R.drawable.checked);//图像资源的ID
			map.put("ItemTitle", BusesList.get(i));
			// map.put("ItemText", "Finished in 1 Min 54 Secs, 70 Moves! ");
			listItem.add(map);
		}
		SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,// 数据源
				R.layout.list_item_1,// ListItem的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "ItemTitle" },
				// ImageItem的XML文件里面的一个ImageView,两个TextView ID
				new int[] { R.id.ItemTitle });
		m_objStationsList.setAdapter(listItemAdapter);
	}

	public void getBusesList(String strStation) {

		ArrayList<String> BusesList = ((CityBusApp) getApplicationContext()).m_objBusScan
				.getStationInfo(strStation);
		showInfo("经过 【" + strStation.trim() + "】的线路共有 "
				+ String.valueOf(BusesList.size()) + " 条");
		// 生成动态数组，加入数据
		ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < BusesList.size(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			// map.put("ItemImage", R.drawable.checked);//图像资源的ID
			map.put("ItemTitle", BusesList.get(i));
			// map.put("ItemText", "Finished in 1 Min 54 Secs, 70 Moves! ");
			listItem.add(map);
		}
		SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,// 数据源
				R.layout.list_item_1,// ListItem的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "ItemTitle" },
				// ImageItem的XML文件里面的一个ImageView,两个TextView ID
				new int[] { R.id.ItemTitle });
		m_objBusesList.setAdapter(listItemAdapter);
	}

	public void showBusesList() {
		String strStation = m_objBusEdit.getText().toString().trim();
		if (strStation.length() == 0)
			return;
		ArrayList<String> BusesList = ((CityBusApp) getApplicationContext()).m_objBusScan
				.ScanString(strStation, false);
		// 生成动态数组，加入数据
		ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < BusesList.size(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			// map.put("ItemImage", R.drawable.checked);//图像资源的ID
			map.put("ItemTitle", BusesList.get(i));
			// map.put("ItemText", "Finished in 1 Min 54 Secs, 70 Moves! ");
			listItem.add(map);
		}
		SimpleAdapterEx listItemAdapter = new SimpleAdapterEx(this, listItem,// 数据源
				R.layout.list_item_1,// ListItem的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "ItemTitle" },
				// ImageItem的XML文件里面的一个ImageView,两个TextView ID
				new int[] { R.id.ItemTitle });
		m_objBusesList.setAdapter(listItemAdapter);
	}

	public void showToolsMsg(String Info) {
		Toast.makeText(this, Info, Toast.LENGTH_SHORT).show();
	}

	public void showInfo(String Info) {
		m_objInfoText.setText(Info.toCharArray(), 0, Info.length());

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// B返回时触发
		switch (requestCode) {
		case REQUEST_FOR_BUSINFO:
			if (resultCode == RESULT_OK) {
				String StationName = data.getExtras().getString("StationName");
				if ("".equals(StationName) == false)
					this.m_objStationEdit.setText(StationName);
			}
			break;
		case REQUEST_FOR_CONFIG:
			Toast.makeText(getApplicationContext(),
					Init() ? "成功应用设置" : "无法加载数据，请检使用最的程序或数据版本",
					Toast.LENGTH_SHORT).show();
			break;
		}
	}

	public boolean Init() {
		if (((CityBusApp) getApplicationContext()).Init()) {
			showInfo("城市："
					+ ((CityBusApp) getApplicationContext()).m_objBusScan.DataName
					+ " 版本："
					+ ((CityBusApp) getApplicationContext()).m_objBusScan.Version
					+ "\n站点总数："
					+ new Integer(
							((CityBusApp) getApplicationContext()).m_objBusScan
									.GetStationsCount()).toString()
					+ "\n线路总数："
					+ new Integer(
							((CityBusApp) getApplicationContext()).m_objBusScan
									.GetBusesCount()).toString());

			return true;
		} else{
			showInfo("当前没有加载任何数所据，请在设置中选择数据，若没有数据，可以在更多数据中找到你要的数据");
			Intent intent = new Intent(getApplicationContext(),ConfigActivity.class);
			startActivityForResult(intent, REQUEST_FOR_CONFIG);
			return false;
		}

	}


	
	
	
	public boolean onCreateOptionsMenu(Menu menu) { 
		menu.add(0, MENU_CONFIG, 0, "设置").setIcon(R.drawable.applications_system);
		menu.add(0, MENU_ABOUT, 0, "关于").setIcon(R.drawable.get_info);     
		menu.add(0, MENU_QUIT, 0, "退出").setIcon(R.drawable.gnome_session_logout);       
		return true; 
		}

	protected void setListener() {
		m_objSearchLines.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				if (null == m_strStationA || m_strStationB == null
						|| "".equals(m_strStationA) || "".equals(m_strStationB)) {
					Toast.makeText(getApplicationContext(), "请先设置起点和终点",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (m_strStationB.equals(m_strStationA)) {
					Toast.makeText(getApplicationContext(), "起点和终点不能一样",
							Toast.LENGTH_SHORT).show();
					return;
				}
				// TODO Auto-generated method stub
				((CityBusApp) getApplicationContext()).m_objBusScan.setHandler(hander);
				((CityBusApp) getApplicationContext()).m_objBusScan.SearchLines(m_strStationA, m_strStationB);

			}
		});
		m_objConfigButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						ConfigActivity.class);
				startActivityForResult(intent, REQUEST_FOR_CONFIG);

			}

		});
		m_objSetStationA.setOnClickListener(new View.OnClickListener() {

			@SuppressWarnings("unchecked")
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(null==m_objStationsList.getAdapter()) return;
				if (m_intStationSelected < 0|| m_intStationSelected >= m_objStationsList.getAdapter().getCount())
					return;
				String station = ((HashMap<String, String>) (m_objStationsList
						.getAdapter().getItem(m_intStationSelected))).get(
						"ItemTitle").toString().trim();
				// //System.out.println(station);
				m_strStationA = station;
				Toast.makeText(getApplicationContext(), station + "被设为起点",
						Toast.LENGTH_SHORT).show();
				Log.d("setOnClickListener", station + "被设为起点");
			}

		});
		m_objSetStationB.setOnClickListener(new View.OnClickListener() {

			@SuppressWarnings("unchecked")
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(null==m_objStationsList.getAdapter()) return;
				if (m_intStationSelected < 0
						|| m_intStationSelected >= m_objStationsList
								.getAdapter().getCount())
					return;
				String station = ((HashMap<String, String>) (m_objStationsList
						.getAdapter().getItem(m_intStationSelected))).get(
						"ItemTitle").toString().trim();
				// showToolsMsg(station + "被设为起点");
				// System.out.println(m_intStationSelected);
				// System.out.println(station);
				m_strStationB = station;
				Toast.makeText(getApplicationContext(), station + "被设为终点",
						Toast.LENGTH_SHORT).show();
				Log.d("setOnClickListener", station + "被设为终点");
			}

		});
		m_objStationsList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						m_intStationSelected = position;
						// System.out.println(m_intStationSelected);
						m_objStationsList.requestFocusFromTouch();
						m_objStationsList.setSelection(position);
					}
				});
		m_objBusesList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@SuppressWarnings("unchecked")
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						m_objBusesList.requestFocusFromTouch();
						m_objBusesList.setSelection(position);
						String strBusName = ((HashMap<String, String>) (m_objBusesList
								.getAdapter().getItem(position))).get(
								"ItemTitle").toString().trim();
						Intent intent = new Intent(getApplicationContext(),
								BusInfoActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString("BusName", strBusName);
						intent.putExtras(bundle);
						startActivityForResult(intent, 0);
					}
				});
		m_objStationsList.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub

				m_objSetStationA.setEnabled(hasFocus);
				m_objSetStationB.setEnabled(hasFocus);

			}

		});
		m_objBusesList.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				// m_intStationSelected = arg2;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});
		m_objStationsList
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@SuppressWarnings("unchecked")
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						m_intStationSelected = arg2;
						// System.out.println(m_intStationSelected);
						String station = ((HashMap<String, String>) (arg0
								.getItemAtPosition(arg2))).get("ItemTitle")
								.toString();
						getBusesList(station);

					}

					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}

				});
		m_objStationEdit.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				showStationsList();
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}
		});
		m_objBusEdit.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				showBusesList();
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}
		});
		m_objStationEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub

			}

		});

	}
	@SuppressWarnings("unused")
	private void sendMsg(int flag,int arg1) {
		sendMsg(flag,arg1,0,null);
	}
	@SuppressWarnings("unused")
	private void sendMsg(int flag) {
		sendMsg(flag,0,0,null);
	}
	private void sendMsg(int flag,int arg1,int arg2,Object object) {
		Message msg = new Message();
		msg.arg1 = arg1;
		msg.arg2 = arg2;
		msg.what = flag;
		msg.obj = object;
		hander.sendMessage(msg);
	}
	
	/* Handles item selections */ 
	public boolean onOptionsItemSelected(MenuItem item) {     
		switch (item.getItemId()) { 
		case MENU_CONFIG:
			Intent intent = new Intent(getApplicationContext(),ConfigActivity.class);
			startActivityForResult(intent, REQUEST_FOR_CONFIG);
			break;
		case MENU_QUIT:         
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(0);
		}            
	return false; 
	}
	

}